package com.amentretenimiento;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import com.amentretenimiento.MyLocation.LocationResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MenuOpciones extends Activity {
	public LocationManager locationManager;
	public TextView tv_nombre;
	public Button bt_inicio, bt_inventario, bt_anomalias, bt_muebles, bt_competencia, bt_exhibiciones, bt_fin;
	public SharedPreferences preferences ;
	public SharedPreferences.Editor editor;
	public int visitada;
	public String miusuario, idagente, idcliente, nombre, idcia, provider, imageInSD = Environment.getExternalStorageDirectory()+"/test.jpg" /*imageInSD = "/mnt/sdcard/test.jpg"*/, hora;
	public Timer tim1, tim2, tim3, tim4, tim5, tim6;
	public double latitute,longitude, latitud_storage, longitude_storege;
	public MyLocation myLocation = new MyLocation();
	public int num;	
	public static final int CAMERA_PIC_REQUEST = 1337; 
	public static Bitmap bm=null;
	public Dialog dialog;
	public ProgressDialog pd;
	//	public String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

	private OrientationEventListener myOrientationEventListener;
	private int orientation = 0;

	
	@Override
	public void onBackPressed() {
		//		boolean internet = isInternetConnectionActive(MenuOpciones.this);
		//		if (internet == true){

		if(myOrientationEventListener!=null)
			myOrientationEventListener.disable();


		if(visitada==1 || visitada==0){
			Log.i("Timers canceled", "Timers canceled");
			if(tim1 != null){
				tim1.cancel();
				tim1.purge();
			}
			if(tim2 != null){
				tim2.cancel();
				tim2.purge();
			}
			if(tim3 != null){
				tim3.cancel();
				tim3.purge();
			}
			if(tim4 != null){
				tim4.cancel();
				tim4.purge();
			}
			if(tim5 != null){
				tim5.cancel();
				tim5.purge();
			}
			if(tim6 != null){
				tim6.cancel();
				tim6.purge();
			}


			editor.putInt("visitada", 0);
			editor.commit();	
			finish();

			//				Intent atras=new Intent(MenuOpciones.this, Nueva.class);
			//				atras.putExtra("idCia", idcia);
			//				atras.putExtra("idagente", idagente);
			//				atras.putExtra("idcliente", idcliente);
			//				atras.putExtra("nombre", nombre);
			//				atras.putExtra("miusuario", miusuario);
			//	
			//				startActivity(atras);
		}else {
			Toast.makeText(this, "Aún no ha finalizado la tienda", Toast.LENGTH_SHORT).show();
		}
		//		}else if(internet == false){
		//            AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
		//			alertdialog.setIcon(R.drawable.icon);
		//	    	alertdialog.setTitle("Aviso");
		//	    	alertdialog.setMessage("Error de conectividad");
		//	    	alertdialog.show();
		//		}



	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_switch);
		inicializeViews();



		myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){

			@Override
			public void onOrientationChanged(int arg0) {
				Log.i("Orientation: ", ""+String.valueOf(arg0));
				orientation = arg0;
				//		     textviewOrientation.setText("Orientation: " + String.valueOf(arg0));
			}
		};


		if (myOrientationEventListener.canDetectOrientation()){
			//				Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
			myOrientationEventListener.enable();
		}else{
//			Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
//			finish();
		}

		/**Para vista horizontal en tablet**/
		//		Display display = getWindowManager().getDefaultDisplay(); 
		//        int width = display.getWidth();  // deprecated
		//        int height = display.getHeight();  // deprecated
		//        if(height > 1000){
		//        	 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		//        }

		//		boolean internet = isInternetConnectionActive(MenuOpciones.this);
		//		if (internet == true){
		Bundle extras = getIntent().getExtras();
		if(extras!=null){
			preferences = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
			editor = preferences.edit();

			//				enable = preferences.getInt("enable", 0);

			visitada=extras.getInt("visitada");

			if(visitada == 1){
				editor.putInt("visitada", visitada);
				editor.commit();
			}else if(visitada == 2){
				editor.putInt("visitada", visitada);
				editor.commit();
			}
			else if(visitada == 0){
				editor.putInt("visitada", visitada);
				editor.commit();
			}
			visitada=preferences.getInt("visitada", 0);
			//				idcia=loginsitesList.getidCia().toString();
			miusuario=extras.getString("miusuario");
			idagente= extras.getString("idagente");
			idcliente= extras.getString("idcliente");
			nombre = extras.getString("nombre");


			SharedPreferences prefs =
					getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

			idcia= prefs.getString("idcia", "0");

			TextView nombre = (TextView) findViewById(R.id.nomtienda);

			//				nombre.setText(extras.getString("nombre"));
			nombre.setText(prefs.getString("nombre", "nulo"));

		}

		if(visitada == 0){
			Log.i("Visitada", "Valor 0");
			bt_anomalias.setEnabled(false);
			bt_competencia.setEnabled(false);
			bt_exhibiciones.setEnabled(false);
			bt_fin.setEnabled(false);
			bt_inicio.setEnabled(false);
			bt_inventario.setEnabled(false);
			bt_muebles.setEnabled(false);
			inicioTimer1();
			inicioTimer2();
		}else if(visitada == 2){
			Log.i("Visitada", "Valor 2");
			bt_anomalias.setEnabled(true);
			bt_competencia.setEnabled(true);
			bt_exhibiciones.setEnabled(true);
			bt_fin.setEnabled(false);
			bt_inicio.setEnabled(false);
			bt_inventario.setEnabled(true);
			bt_muebles.setEnabled(true);
			inicioTimer4();
			inicioTimer5();
		}else if(visitada == 1){
			Log.i("Visitada", "Valor 1");
			bt_anomalias.setEnabled(true);
			bt_competencia.setEnabled(true);
			bt_exhibiciones.setEnabled(true);
			bt_fin.setEnabled(false);
			bt_inicio.setEnabled(false);
			bt_inventario.setEnabled(true);
			bt_muebles.setEnabled(true);				
		}

		bt_inicio.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean internet = isInternetConnectionActive(MenuOpciones.this);
				if (internet == true){
					Log.i("cancel Timer 3", "cancel Timer 3");
					tim3.cancel();
					tim3.purge();
					Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
					//					File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
					SharedPreferences prefs = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
					String nomtiendacod = prefs.getString("nombre", "nulo");	
					Calendar mical=Calendar.getInstance();
					String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
					hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

					File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"E_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");



					Uri outputFileUri = Uri.fromFile(file);
					cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
					Log.i("URI PHOTO", outputFileUri.toString());
					startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
					num = 1;

				}else if(internet == false){
					AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
					alertdialog.setIcon(R.drawable.icon);
					alertdialog.setTitle("Aviso");
					alertdialog.setMessage("Error de conectividad");
					alertdialog.show();
				}

			}


		});


		bt_inventario.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//					boolean internet = isInternetConnectionActive(MenuOpciones.this);
				//					if (internet == true){
				//					if(tim6 != null){
				//						Log.i("cancel Timer 6", "cancel Timer 6");
				//						tim6.cancel();
				//						tim6.purge();
				//					}else if(tim4 != null || tim5 != null){
				//						Log.i("cancel Timer 4", "cancel Timer 4");
				//						Log.i("cancel Timer 5", "cancel Timer 5");
				//						tim4.cancel();
				//						tim4.purge();							
				//						tim5.cancel();
				//						tim5.purge();
				//
				//					}

				//						Toast.makeText(getApplicationContext(), "La tienda ya se ha iniciado", Toast.LENGTH_SHORT).show();
				Intent goInventario=new Intent(MenuOpciones.this, Inventario.class);
				Bundle extras = getIntent().getExtras();
				String nombre= extras.getString("nombre");
				goInventario.putExtra("nombre", nombre);
				goInventario.putExtra("idCia", idcia);
				goInventario.putExtra("idCliente", idcliente);
				goInventario.putExtra("idAgente", idagente);
				goInventario.putExtra("miusuario", miusuario);
				goInventario.putExtra("visitada", visitada);
				startActivity(goInventario);
			}
		});

		bt_anomalias.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//					if(tim6 != null){
				//						Log.i("cancel Timer 6", "cancel Timer 6");
				//						tim6.cancel();
				//						tim6.purge();
				//					}else if(tim4 != null || tim5 != null){
				//						Log.i("cancel Timer 4", "cancel Timer 4");
				//						Log.i("cancel Timer 5", "cancel Timer 5");
				//						tim4.cancel();
				//						tim4.purge();							
				//						tim5.cancel();
				//						tim5.purge();
				//					}
				Intent goInventario=new Intent(MenuOpciones.this, Quejas.class);
				Bundle extras = getIntent().getExtras();
				String nombre= extras.getString("nombre");
				goInventario.putExtra("nombre", nombre);
				goInventario.putExtra("idCia", idcia);
				goInventario.putExtra("idCliente", idcliente);
				goInventario.putExtra("idAgente", idagente);
				goInventario.putExtra("miusuario", miusuario);
				goInventario.putExtra("visitada", visitada);
				startActivity(goInventario);
			}				

		});

		bt_competencia.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean internet = isInternetConnectionActive(MenuOpciones.this);
				if (internet == true){
					//						if(tim6 != null){
					//							Log.i("cancel Timer 6", "cancel Timer 6");
					//							tim6.cancel();
					//							tim6.purge();
					//						}else if(tim4 != null || tim5 != null){
					//							Log.i("cancel Timer 4", "cancel Timer 4");
					//							Log.i("cancel Timer 5", "cancel Timer 5");
					//							tim4.cancel();
					//							tim4.purge();							
					//							tim5.cancel();
					//							tim5.purge();
					//
					//						}
					Intent goInventario=new Intent(MenuOpciones.this, Competencia.class);
					Bundle extras = getIntent().getExtras();
					String nombre= extras.getString("nombre");
					goInventario.putExtra("nombre", nombre);
					goInventario.putExtra("idCia", idcia);
					goInventario.putExtra("idCliente", idcliente);
					goInventario.putExtra("idAgente", idagente);
					goInventario.putExtra("miusuario", miusuario);
					goInventario.putExtra("visitada", visitada);
					startActivity(goInventario);
				}else if(internet == false){
					AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
					alertdialog.setIcon(R.drawable.icon);
					alertdialog.setTitle("Aviso");
					alertdialog.setMessage("Error de conectividad");
					alertdialog.show();
				}	
			}
		});
		bt_exhibiciones.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean internet = isInternetConnectionActive(MenuOpciones.this);
				if (internet == true){
					//						if(tim6 != null){
					//							Log.i("cancel Timer 6", "cancel Timer 6");
					//							tim6.cancel();
					//							tim6.purge();
					//						}else if(tim4 != null || tim5 != null){
					//							Log.i("cancel Timer 4", "cancel Timer 4");
					//							Log.i("cancel Timer 5", "cancel Timer 5");
					//							tim4.cancel();
					//							tim4.purge();							
					//							tim5.cancel();
					//							tim5.purge();
					//
					//						}
					Intent goMuebles=new Intent(MenuOpciones.this, Exhibiciones.class);
					Bundle extras = getIntent().getExtras();
					String nombre= extras.getString("nombre");
					goMuebles.putExtra("nombre", nombre);
					goMuebles.putExtra("idAgente", idagente);
					goMuebles.putExtra("idCliente", idcliente);
					goMuebles.putExtra("idCia", idcia);
					goMuebles.putExtra("miusuario", miusuario);
					goMuebles.putExtra("visitada", visitada);
					startActivity(goMuebles);
				}else if(internet == false){
					AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
					alertdialog.setIcon(R.drawable.icon);
					alertdialog.setTitle("Aviso");
					alertdialog.setMessage("Error de conectividad");
					alertdialog.show();
				}	
			}
		});
		bt_muebles.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//					if(tim6 != null){
				//						Log.i("cancel Timer 6", "cancel Timer 6");
				//						tim6.cancel();
				//						tim6.purge();
				//					}else if(tim4 != null || tim5 != null){
				//						Log.i("cancel Timer 4", "cancel Timer 4");
				//						Log.i("cancel Timer 5", "cancel Timer 5");
				//						tim4.cancel();
				//						tim4.purge();							
				//						tim5.cancel();
				//						tim5.purge();
				//
				//					}
				Intent goMuebles=new Intent(MenuOpciones.this, Muebles.class);
				Bundle extras = getIntent().getExtras();
				String nombre= extras.getString("nombre");
				goMuebles.putExtra("nombre", nombre);
				goMuebles.putExtra("idAgente", idagente);
				goMuebles.putExtra("idCliente", idcliente);
				goMuebles.putExtra("idCia", idcia);
				goMuebles.putExtra("miusuario", miusuario);
				goMuebles.putExtra("visitada", visitada);

				startActivity(goMuebles);
			}				
		});


		bt_fin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean internet = isInternetConnectionActive(MenuOpciones.this);
				if (internet == true){
					Log.i("cancel Timer 6", "cancel Timer 6");
					if(tim6 != null){
						tim6.cancel();
						tim6.purge();
					}

					Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  

					SharedPreferences prefs = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
					String nomtiendacod = prefs.getString("nombre", "nulo");	
					Calendar mical=Calendar.getInstance();
					String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
					hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

					File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"S_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");
					Uri outputFileUri = Uri.fromFile(file);
					cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
					Log.i("URI PHOTO", outputFileUri.toString());
					startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
					num = 2;
				}else if(internet == false){
					AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
					alertdialog.setIcon(R.drawable.icon);
					alertdialog.setTitle("Aviso");
					alertdialog.setMessage("Error de conectividad");
					alertdialog.show();
				}	
			}
		});

		//		}else{
		//
		//		}


	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if(resultCode == RESULT_CANCELED){
				Toast.makeText(getApplicationContext(), "No se ha tomado la foto", Toast.LENGTH_LONG).show();
				if(num == 1){
					inicioTimer3();

				}else if(num == 2){
					//				inicioTimer6();

				}
			}else{

				if (requestCode == CAMERA_PIC_REQUEST) {
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 4;    // this will cut the sampling by 25% 
					Bitmap bmap = null;
					SharedPreferences prefs = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
					final String nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
					Calendar mical=Calendar.getInstance();
					final String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
					if(num == 1){
						Log.i("NOMBRE FOTO",Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"E_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg" );
						imageInSD = Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"E_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg";
						bmap = BitmapFactory.decodeFile(imageInSD,options);

					}else if(num == 2){
						Log.i("NOMBRE FOTO",Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"S_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg" );
						imageInSD = Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"S_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg";
						bmap = BitmapFactory.decodeFile(imageInSD,options);

					}

					//					
					//					
					//			SharedPreferences prefs =




					int width = bmap.getWidth();
					int height = bmap.getHeight();
					Log.i("Ancho de archivo", ""+width);
					Log.i("Alto de archivo", ""+height);
					int newWidth;
					int newHeight;
					if(width < height){
						newWidth = 600;
						newHeight =800 ;
					}else{
						newWidth = 800;
						newHeight = 600;
					}
					float scaleWidth = ((float) newWidth) / width;
					float scaleHeight = ((float) newHeight) / height;
					// createa matrix for the manipulation
					Matrix matrix = new Matrix();
					// resize the bit map
					matrix.postScale(scaleWidth, scaleHeight);
					
					
					if(orientation <= 45 || (orientation> 315 && orientation<360)){
						matrix.postRotate(90);
					}else{
						matrix.postRotate(0);
					}
					
					
					// recreate the new Bitmap
					bm = Bitmap.createBitmap(bmap, 0, 0,
							width, height, matrix, true);
					Log.i("Bitmap getWidth", ""+bm.getWidth());
					Log.i("Bitmap getHeight", ""+bm.getHeight());
					int newWidth2,newHeight2;
					if(bm.getWidth() < bm.getHeight()){
						newWidth2 = 135;
						newHeight2 = 181;
					}else{
						newWidth2 = 181;
						newHeight2 = 135;
					}
					float scaleWidth2 = ((float) newWidth2) / width;
					float scaleHeight2 = ((float) newHeight2) / height;
					// createa matrix for the manipulation
					Matrix matrix2 = new Matrix();
					// resize the bit map
					matrix2.postScale(scaleWidth2, scaleHeight2);

					Bitmap bmapa = Bitmap.createBitmap(bmap, 0, 0,
							width, height, matrix2, true);

					dialog=new Dialog(MenuOpciones.this);
					dialog.setContentView(R.layout.custom_dial);
					dialog.setTitle("¿ Es correcta la foto ?");
					ImageView image = (ImageView) dialog.findViewById(R.id.imageView1);  
					image.setImageBitmap(bmapa); 
					dialog.show();
					Button botonina = (Button) dialog.findViewById(R.id.button1);
					botonina.setOnClickListener(new OnClickListener() {
						@SuppressWarnings("deprecation")
						@Override
						public void onClick(View v) {
							try {
								boolean internet = isInternetConnectionActive(MenuOpciones.this);
								if (internet == true){
									if(num == 1) {
										dialog.dismiss();
										dialog.cancel();
										editor.putInt("visitada", 2);
										editor.commit();
										bt_inicio.setEnabled(false);
										bt_inventario.setEnabled(true);
										bt_anomalias.setEnabled(true);
										bt_competencia.setEnabled(true);
										bt_exhibiciones.setEnabled(true);
										bt_muebles.setEnabled(true);
										//					fin.setEnabled(true);
										bt_fin.setEnabled(false);

										try {
											if(bm != null)
											{
												new UploadClass().execute("");
											}else{
												AlertDialog.Builder builder = new AlertDialog.Builder(MenuOpciones.this);
												builder.setMessage("No se ha capturado la foto")
												.setCancelable(false)
												.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
													public void onClick(DialogInterface dialog, int id) {
														// put your code here
													}
												});

												AlertDialog alertDialog = builder.create();
												alertDialog.show();

											}
										} catch (Exception e) {
											e.printStackTrace();
										}				


									}
									else if(num == 2){
										dialog.cancel();

										try {
											if(bm != null)
											{
												new UploadClass().execute("");

											}else{
												AlertDialog.Builder builder = new AlertDialog.Builder(MenuOpciones.this);
												builder.setMessage("No se ha capturado la foto")
												.setCancelable(false)
												.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
													public void onClick(DialogInterface dialog, int id) {
														// put your code here
													}
												});

												AlertDialog alertDialog = builder.create();
												alertDialog.show();

											}
										} catch (Exception e) {
											e.printStackTrace();
										}				


									}

								}else if(internet == false){
									AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
									alertdialog.setIcon(R.drawable.icon);
									alertdialog.setTitle("Aviso");
									alertdialog.setMessage("Error de conectividad");
									alertdialog.show();
								}
							} catch (final Exception e) {
								e.printStackTrace();
								Intent intent = new Intent(Intent.ACTION_SEND);
								intent.setType("message/rfc822");
								intent.putExtra(Intent.EXTRA_SUBJECT, "AM ANDROID");
								intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"joseluis@smartthinking.com.mx"});
								intent.putExtra(Intent.EXTRA_TEXT, "Mensaje Error  ---> "+e.getMessage().toString());
								Intent mailer = Intent.createChooser(intent, null);
								startActivity(mailer);

								//								AlertDialog alertdialog=new AlertDialog.Builder(MenuOpciones.this).create();
								//								alertdialog.setIcon(R.drawable.icon);
								//								alertdialog.setTitle("Aviso");
								//								alertdialog.setMessage("Alerta Excepci�n");
								//								alertdialog.setButton("Enviar", new DialogInterface.OnClickListener() {
								//
								//									@Override
								//									public void onClick(DialogInterface dialog, int which) {
								//										Intent intent = new Intent(Intent.ACTION_SEND);
								//										intent.setType("message/rfc822");
								//										intent.putExtra(Intent.EXTRA_SUBJECT, "AM ANDROID");
								//										intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"joseluis@smartthinking.com.mx"});
								//										intent.putExtra(Intent.EXTRA_TEXT, "Mensaje Error  ---> "+e.toString());
								//										Intent mailer = Intent.createChooser(intent, null);
								//										startActivity(mailer);
								//
								//
								//									}
								//								});
								//								alertdialog.show();


							}



						}



					});

					Button botootra = (Button) dialog.findViewById(R.id.button2);
					botootra.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
							dialog.cancel();
							Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
//							File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
							File file = null;

							if(num == 1){
								file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"E_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");
							}else{
								file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nomtiendacod.toUpperCase()+"_"+idagente+"_"+"S_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");
							}
							
							
							Uri outputFileUri = Uri.fromFile(file);
							cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);


							Log.i("URI PHOTO", outputFileUri.toString());
							startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  


						}
					});

				}

			}
		} catch (Exception e) {
			e.printStackTrace();

			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("message/rfc822");
			intent.putExtra(Intent.EXTRA_SUBJECT, "AM ANDROID");
			intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"joseluis@smartthinking.com.mx"});
			intent.putExtra(Intent.EXTRA_TEXT, "Mensaje Error  ---> "+e.toString());
			Intent mailer = Intent.createChooser(intent, null);
			startActivity(mailer);
		}





	}


	/*****LocationResult*****/
	public LocationResult locationResult = new LocationResult(){
		public void gotLocation(final Location location){
			latitute=location.getLatitude();
			longitude=location.getLongitude();
			latitud_storage=latitute;
			longitude_storege=longitude;
			Log.i("LOCATION LAT", ""+latitute);
			Log.i("LOCATION LON", ""+longitude);
			Log.i("PROVIDER", ""+location.getProvider());
			provider=location.getProvider();
		}; 
	};

	/*****Solicitar localización*****/
	private void locationClick() {
		myLocation.getLocation(this, locationResult);
	}

	/*****Inicio Timer 1*****/
	private void inicioTimer1() {
		Log.i("Inicio Timer 1", "Inicio Timer 1");
		locationClick();
		tim1 = new Timer();
		tim1.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.i("Timer 1 task", "Timer 1 task");
				chequeo();
			}
		}, 0, 10000);
	}

	/*****Inicio Timer 2*****/
	private void inicioTimer2() {
		Log.i("Inicio Timer 2", "Inicio Timer 2");
		tim2 = new Timer();
		tim2.schedule(new TimerTask() {

			@Override
			public void run() {
				mihandler.sendEmptyMessage(1);
				Log.i("Timer 2 task", "Timer 2 task");

			}
		}, 75000);		
	}

	/*****Inicio Timer 3*****/
	private void inicioTimer3() {
		Log.i("Inicio Timer 3", "Inicio Timer 3");
		tim3 = new Timer();
		tim3.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.i("Timer 3 task", "Timer 3 task");
				mihandler.sendEmptyMessage(2);
			}
		}, 60000);
	}


	/*****Inicio Timer 4*****/
	private void inicioTimer4() {
		latitute=0;
		longitude=0;
		Log.i("Inicio Timer 4", "Inicio Timer 4");
		locationClick();
		tim4 = new Timer();
		tim4.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.i("Timer 4 task", "Timer 4 task");
				chequeo2();
			}
		}, 0, 10000);
	}


	/*****Inicio Timer 5*****/
	private void inicioTimer5() {
		Log.i("Inicio Timer 5", "Inicio Timer 5");
		tim5 = new Timer();
		tim5.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.i("cancel Timer 4", "cancel Timer 4");
				Log.i("cancel Timer 5", "cancel Timer 5");

				tim4.cancel();
				tim4.purge();
				tim5.cancel();
				tim5.purge();
				//*******coordanteriores=1;****/
				//use coordenadas anteriores
				mihandler.sendEmptyMessage(3);
				Log.i("Timer 5 task", "Timer 5 task");

			}
		}, 75000);		
	}

	/*****Inicio Timer 6*****/
	private void inicioTimer6() {
		Log.i("Inicio Timer 6", "Inicio Timer 6");
		tim6 = new Timer();
		tim6.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.i("cancel Timer 6", "cancel Timer 6");
				tim6.cancel();
				tim6.purge();
				Log.i("Timer 6 task", "Timer 6 task");
				mihandler.sendEmptyMessage(4);
			}
		}, 60000);
	}

	/***Chequeo posición***/
	protected void chequeo() {
		if(longitude != 0){
			Log.i("Chequeo coordenadas", "Chequeo coordenadas");
			mihandler.sendEmptyMessage(0);
			Log.i("cancel Timer 1", "cancel Timer 1");
			Log.i("cancel Timer 2", "cancel Timer 2");
			tim1.cancel();
			tim1.purge();
			tim2.cancel();
			tim2.purge();
			inicioTimer3();
		}			
	}

	/***Chequeo posición***/
	protected void chequeo2() {
		if(longitude != 0){
			Log.i("Chequeo coordenadas 2", "Chequeo coordenadas 2");
			mihandler.sendEmptyMessage(3);
			Log.i("cancel Timer 4", "cancel Timer 4");
			Log.i("cancel Timer 5", "cancel Timer 5");
			tim4.cancel();
			tim4.purge();
			tim5.cancel();
			tim5.purge();
			inicioTimer6();
		}			
	}



	Handler mihandler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case 0:
				bt_inicio.setEnabled(true);

				break;

			case 1:
				AlertDialog.Builder builder1 = new AlertDialog.Builder(MenuOpciones.this);
				builder1.setMessage("No obtuvierón las coordenadas. Regrese y vuelva a intentar.")
				.setCancelable(false)
				.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Log.i("cancel Timer 1", "cancel Timer 1");
						Log.i("cancel Timer 2", "cancel Timer 2");
						tim1.cancel();
						tim1.purge();
						tim2.cancel();	
						tim2.purge();
						onBackPressed();
					}
				});
				AlertDialog alertDialog1 = builder1.create();
				alertDialog1.show();			
				break;

			case 2:
				AlertDialog.Builder builder2 = new AlertDialog.Builder(MenuOpciones.this);
				builder2.setMessage("Se terminó el tiempo para dar inicio")
				.setCancelable(false)
				.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Log.i("cancel Timer 3", "cancel Timer 3");
						tim3.cancel();
						tim3.purge();
						onBackPressed();
					}
				});
				AlertDialog alertDialog2 = builder2.create();
				alertDialog2.show();	
				break;

			case 3:
				bt_fin.setEnabled(true);
				break;


			case 4:
				bt_fin.setEnabled(false);
				inicioTimer4();
				inicioTimer5();
				break;


			default:
				break;
			}

		};
	};

	@Override
	protected void onResume() {
		super.onResume();
		gps();
	}




	private void inicializeViews() {
		SharedPreferences prefs = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

		tv_nombre = (TextView) findViewById(R.id.nomtienda);
		bt_inicio = (Button) findViewById(R.id.inicio);
		bt_competencia = (Button) findViewById(R.id.competencia);
		bt_inventario = (Button) findViewById(R.id.inventario);
		bt_anomalias = (Button) findViewById(R.id.quejas);
		bt_muebles = (Button) findViewById(R.id.muebles);
		bt_exhibiciones = (Button) findViewById(R.id.exhibiciones);
		bt_fin = (Button) findViewById(R.id.finalizar);

		tv_nombre.setText(prefs.getString("nombre", "nulo"));

	}



	public void gps(){
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if((!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) || 
				(!locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) )
		{

			AlertDialog.Builder builder = new AlertDialog.Builder(MenuOpciones.this);
			builder.setMessage("Debe activar satélites GPS y redes inalámbricas")
			.setCancelable(false)
			.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
					startActivity(myIntent);  
					dialog.cancel();
					dialog.dismiss();
				}
			})
			.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
					dialog.cancel();
					onBackPressed();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
	}

	public static boolean isInternetConnectionActive(Context context) {
		boolean bool = false;

		NetworkInfo networkInfo = ((ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();

		if(networkInfo == null || !networkInfo.isConnected()) {
			return false;
		}
		return true;
	}


	public class UploadClass extends AsyncTask<String, String, String>{

		@Override
		protected void onPreExecute() {
			Log.i("preexecute", "preexecute");
			pd = ProgressDialog.show(MenuOpciones.this, "Espere por favor", "Cargando..", true, true, new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					onBackPressed();
				}
			});			

		}


		@Override
		protected String doInBackground(String... params) {
			Log.i("doinback", "doinback");

			try {
				executeMultipartPost();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}


		@Override
		protected void onPostExecute(String result) {
			Log.i("postexecute", "postexecute");

			pd.dismiss();
			Toast.makeText(getApplicationContext(), "Envío de archivo terminado", Toast.LENGTH_LONG).show();
			bt_fin.setEnabled(true);
			//			inicioTimer4();
			//			inicioTimer5();

		}


	}



	public void executeMultipartPost() throws Exception {
		try {
			Calendar mical=Calendar.getInstance();
			String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
			hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);

			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(urlamentretenimiento+"AMEntretenimiento/UploadServlet");

			if(num == 1){
				SharedPreferences prefs =
						getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

				String nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
				Log.i("CADENACODIF", ""+nomtiendacod);

				ByteArrayBody bab = new ByteArrayBody(data, nomtiendacod.toUpperCase()+"_"+idagente+"_"+"E_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");
				Log.i("NOMBRE FOTO",nomtiendacod.toUpperCase()+"_"+idagente+"_"+"E_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg" );


				MultipartEntity reqEntity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);

				reqEntity.addPart("uploaded", bab);
				reqEntity.addPart("tipo", new StringBody("I"));

				idcia= prefs.getString("idcia", "0");

				reqEntity.addPart("idcia", new StringBody(idcia));
				reqEntity.addPart("idagente", new StringBody(""+idagente));
				//					reqEntity.addPart("idcliente", new StringBody(""+idcliente));
				reqEntity.addPart("idcliente", new StringBody(""+prefs.getString("idcliente", "0")));
				reqEntity.addPart("lat", new StringBody(""+latitute));
				reqEntity.addPart("lng", new StringBody(""+longitude));
				reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));

				Log.i("CONTENT LENGHT", ""+reqEntity.getContentLength());

				postRequest.setEntity(reqEntity);

				refresh('E');

				HttpResponse response = httpClient.execute(postRequest);
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent(), "UTF-8"));
				String sResponse;
				StringBuilder s = new StringBuilder();

				while ((sResponse = reader.readLine()) != null) {
					s = s.append(sResponse);

				}
				System.out.println("Response: " + s);

			}

			if(num == 2){

				SharedPreferences prefs =
						getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

				String nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
				Log.i("CADENACODIF", ""+nomtiendacod);

				ByteArrayBody bab = new ByteArrayBody(data, nomtiendacod.toUpperCase()+"_"+idagente+"_"+"S_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");
				Log.i("NOMBRE FOTO",nomtiendacod.toUpperCase()+"_"+idagente+"_"+"S_"+fec+"_"+hora+"_"+provider.toUpperCase()+".jpeg");


				MultipartEntity reqEntity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);


				reqEntity.addPart("uploaded", bab);
				reqEntity.addPart("tipo", new StringBody("F"));
				//				SharedPreferences prefs =
				//					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

				idcia= prefs.getString("idcia", "0");
				reqEntity.addPart("idcia", new StringBody(idcia));

				reqEntity.addPart("idagente", new StringBody(""+idagente));
				reqEntity.addPart("idcliente", new StringBody(""+idcliente));
				reqEntity.addPart("lat", new StringBody(""+latitute));
				reqEntity.addPart("lng", new StringBody(""+longitude));

				reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
				Log.i("CONTENT LENGHT", ""+reqEntity.getContentLength());

				postRequest.setEntity(reqEntity);

				refresh('S');


				HttpResponse response = httpClient.execute(postRequest);

				BufferedReader reader = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent(), "UTF-8"));
				String sResponse;
				StringBuilder s = new StringBuilder();

				while ((sResponse = reader.readLine()) != null) {
					s = s.append(sResponse);

				}
				System.out.println("Response: " + s);
				//				Log.i("ITEM", item.toString());
				editor.putInt("visitada", 0);
				editor.commit();

				//		    	 insert();
				finish();

				//				Intent goListaTiendas=new Intent(MenuOpciones.this, Nueva.class);
				//
				//				goListaTiendas.putExtra("idCia", idcia);
				//				goListaTiendas.putExtra("idagente", idagente);
				//				goListaTiendas.putExtra("idcliente", idcliente);
				//				goListaTiendas.putExtra("nombre", nombre);
				//				goListaTiendas.putExtra("miusuario", miusuario);
				//
				//				goListaTiendas.putExtra("item", preferences.getString("itemlista", ""));
				//
				//				startActivity(goListaTiendas);

				//				  editor.putInt("visitada", visitada);

				// insert();

				//				handler.sendEmptyMessage(0);


			}

		} catch (Exception e) {
			e.printStackTrace();
			//Log.e(e.getClass().getName(), e.getMessage());
		}

	}

	public static String remove1(String input) {
		// Cadena de caracteres original a sustituir.
		String original = "áàäéèëíìïóòöúùuñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑçÇ";		// Cadena de caracteres ASCII que reemplazar�n los originales.
		String ascii = "aaaeeeiiiooouuunAAAEEEIIIOOOUUUNcC";
		String output = input;
		for (int i=0; i<original.length(); i++) {
			// Reemplazamos los caracteres especiales.
			output = output.replace(original.charAt(i), ascii.charAt(i));
		}//for i
		return output;
	}//remove1


	private void refresh(char proceso) {
		//delete from gps where convert(varchar,fecha,111) = convert(varchar,getdate(),111) and idAgente = 5082 and idCliente = 5988 and proceso = 'E'
		// For using Internet methods, AndroidManifest.xml must have the following permission:
		//<uses-permission android:name="android.permission.INTERNET"/>
		URI myURI = null;
		SharedPreferences prefs = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

		try {

			myURI = new URI(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
					"Command=delete+from+gps+where+convert(varchar,fecha,111)=" +
					//					"convert(varchar,getdate(),111)+and+idAgente="+idagente+"+and+idCliente="+idcliente+"+and+proceso='"+proceso+"'");
					"convert(varchar,getdate(),111)+and+idAgente="+idagente+"+and+idCliente="+""+prefs.getString("idcliente", "0")+"+and+proceso='"+proceso+"'");




		} catch (URISyntaxException e) {
			// Deal with it
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);
			Log.i("EXECUTE GET", urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
					"Command=delete+from+gps+where+convert(varchar,fecha,111)=" +
					//					"convert(varchar,getdate(),111)+and+idAgente="+idagente+"+and+idCliente="+idcliente+"+and+proceso='"+proceso+"'");
					"convert(varchar,getdate(),111)+and+idAgente="+idagente+"+and+idCliente="+""+prefs.getString("idcliente", "0")+"+and+proceso='"+proceso+"'");

		} catch (IOException e) {
		}

		HttpEntity httpEntity = webServerResponse.getEntity();

		if (httpEntity != null) {
			// You have your response; handle it. For instance, with an input
			// stream
			// InputStream input = entity.getContent();
		}

	}

}
















